package world.player;

import gui.gui2d.Promotion;
import gui.gui2d.highLevelPanels.utils.GuiTrigger;

import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import multiplayer.lan.CloseConnection;
import multiplayer.lan.Move;
import multiplayer.lan.TcpClient;
import multiplayer.lan.TcpObject;
import multiplayer.lan.TcpServer;
import multiplayer.lan.utility.Message;
import utility.Color;
import utility.EventPass;
import utility.NameMemmory;
import utility.Point;
import world.ChessBoardMenager;
import world.Piece;
import world.gameMenager.GameManager;

public class RemotePlayer extends Player implements Observer{
	boolean iPlayng=false;
	private TcpObject connectionInstance;
	public RemotePlayer(Color color, TcpObject connectionInstance) {
		super(color);
		this.connectionInstance=connectionInstance;
	}
	@Override
	public void move(Point from, Point to) {
		if(gameManager.canMove(this)){
			gameManager.move(this, from, to);
		}else{
			System.out.println("You can't move now");
		}

	}

	@Override
	public void update(Observable o, Object arg) {
		if(o instanceof TcpClient || o instanceof TcpServer){
			if(arg instanceof Move){
				Move ep= (Move) arg;
				ChessBoardMenager cbm = gameManager.getChess().getChessBoardMenager();
				if(cbm.getMatrix()[ep.getFrom().getX()][ep.getFrom().getY()].getColor().equals(this.color)){
					move(ep.getFrom(),ep.getTo());
				}
			}
			if(arg instanceof Message){
				Message mess= (Message) arg;
				gameManager.receiveMessageFromRemotePlayer(mess);
			}
			if(arg instanceof Promotion){
				Promotion piece= (Promotion) arg;
				gameManager.receivePromotionFromLan(piece.getPiecePromotion());
				
			}
			if(arg instanceof CloseConnection){
				CloseConnection cl = (CloseConnection) arg;
				gameManager.connectionLost(cl.getMessage());
				
			}

		}
		if(o instanceof GameManager){
			if(arg instanceof Move){
				Move m= (Move)arg;
				if(m.getPlayer()!=this){
					try {
						System.out.println("Send on lan movement: "+m.getFrom()+" "+ m.getTo());
						connectionInstance.sendMovement(m.getFrom(), m.getTo());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			if(arg instanceof Promotion){
				Promotion p = (Promotion) arg;
				System.out.println(p);
				connectionInstance.sendPromotion(p);
			}
			if(arg instanceof GuiTrigger){
				GuiTrigger g = (GuiTrigger) arg;
				if(g.getId().equals(GuiTrigger.MESSAGE_FROM_LOCAL)){
					String p = (String)g.getDate();
					try {
						connectionInstance.sendMessage(NameMemmory.getInstace().getName(), p);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}


}
